package cn.itsource.common.util;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * JWT 密钥的解析和加密 工具类
 */
public class JwtUtils {

    private static final String JWT_PAYLOAD_USER_KEY = "user";


    private static String createJTI() {
        return new String(Base64.getEncoder()
        	.encode(UUID.randomUUID().toString().getBytes()));
    }
    /**
     * 私钥加密token
     *
     * @param loginData   载荷中的数据
     * @param privateKey 私钥
     * @param expire     过期时间，单位分钟
     * @return JWT
     */
    public static String generateTokenExpireInMinutes(Object loginData, PrivateKey privateKey, int expire) {
        return Jwts.builder()
                .claim(JWT_PAYLOAD_USER_KEY, JSONObject.toJSONString(loginData))
                .setId(createJTI())
                //当前时间往后加多少分钟
                .setExpiration(DateTime.now().plusMinutes(expire).toDate())
                .signWith(SignatureAlgorithm.RS256,privateKey)
                .compact();

    }

    /**
     * 私钥加密token
     *
     * @param loginData   载荷中的数据
     * @param privateKey 私钥
     * @param expire     过期时间，单位秒
     * @return JWT
     */
    public static String generateTokenExpireInSeconds(Object loginData, PrivateKey privateKey, int expire) {
        return Jwts.builder()
                .claim(JWT_PAYLOAD_USER_KEY, JSONObject.toJSONString(loginData))
                .setId(createJTI())
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.RS256,privateKey)
                .compact();
    }

    public static String generateTokenExpireInSeconds(Object loginData,int expire) {
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            return generateTokenExpireInSeconds(loginData,privateKey,expire);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 公钥解析token
     *
     * @param token     用户请求中的token
     * @param publicKey 公钥
     * @return Jws<Claims>
     */
    private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }


    /**
     * 获取token中的用户信息
     *
     * @param token  用户请求中的令牌
     * @param publicKey 公钥
     * @return 用户信息
     */
    public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey, Class<T> userType) {
        Jws<Claims> claimsJws = parserToken(token, publicKey);
        Claims body = claimsJws.getBody();
        Payload<T> claims = new Payload<>();
        claims.setId(body.getId());
        T t = JSONObject.parseObject(body.get(JWT_PAYLOAD_USER_KEY).toString(),userType);
        claims.setLoginData(t);
        claims.setExpiration(body.getExpiration());
        return claims;
    }

    public static <T> Payload<T> getInfoFromToken(String token, Class<T> userType) {
        try {
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
            return getInfoFromToken(token,publicKey,userType);
        } catch (Exception e) {
            e.printStackTrace();
        }
       return null;
    }

    /**
     * 获取token中的载荷信息
     *
     * @param token     用户请求中的令牌
     * @param publicKey 公钥
     * @return 用户信息
     */
    public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey) {
        Jws<Claims> claimsJws = parserToken(token, publicKey);
        Claims body = claimsJws.getBody();
        Payload<T> claims = new Payload<>();
        claims.setId(body.getId());
        claims.setExpiration(body.getExpiration());
        return claims;
    }

    public static String compressToken(String token) {
        try {
            byte[] input = token.getBytes("UTF-8");
            Deflater compressor = new Deflater();
            compressor.setInput(input);
            compressor.finish();
            byte[] output = new byte[input.length];
            int compressedDataLength = compressor.deflate(output);
            compressor.end();
            return Base64.getUrlEncoder().withoutPadding().encodeToString(output);
        } catch (Exception e) {
            throw new RuntimeException("Failed to compress token", e);
        }
    }

    public static String decompressToken(String compressedToken) {
        try {
            byte[] input = Base64.getUrlDecoder().decode(compressedToken);
            Inflater decompressor = new Inflater();
            decompressor.setInput(input);
            byte[] output = new byte[input.length];
            int decompressedDataLength = decompressor.inflate(output);
            decompressor.end();
            return new String(output, 0, decompressedDataLength, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("Failed to decompress token", e);
        }
    }


    public static void main(String[] args) throws Exception {
        // 1 获取token
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
        System.out.println(privateKey);

        Map<String,Object> map = new HashMap<>();
        map.put("username","张三");
        map.put("password",123456);
        String token = generateTokenExpireInSeconds(map, privateKey, 10);
        System.out.println(token);//token
//
//        // 2 解析token里面内容
        PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
        Payload<Object> payload = getInfoFromToken(token, publicKey, Object.class);
        System.out.println(payload);
        Map<String,Object> loginData = (Map)payload.getLoginData();
        System.out.println(loginData.get("username").toString()+loginData.get("password").toString());
        Thread.sleep(11000); //超时后继续解析
        payload = getInfoFromToken(token, publicKey, Object.class);
        System.out.println(payload);

    }

}